package db

import (
	"yunpan/cache/log"
	mydb "yunpan/db/mysql"
)

type User struct {
	Username string
	Email string
	Phone string
	SignupAt string
	LastActiveAt string
	Status int
}

func UserSignup(username string, pwd string) bool {
	stmt, err := mydb.DBConn().Prepare("insert ignore into tbl_user "+
		" (`user_name`, `user_pwd`) values(?,?) ")
	if err != nil {
		log.Ob().Warn("failed usersignup prepared")
		return false
	}
	defer stmt.Close()

	ret, err := stmt.Exec(username, pwd)
	if err != nil {
		log.Ob().Warn("insert user failed")
		return false
	}
	if rowsAffected, err := ret.RowsAffected(); nil == err && rowsAffected > 0 {
		return true
	}
	return false
}

func UserSignin(username, pwd_enc string) bool {
	stmt, err := mydb.DBConn().Prepare("select * from tbl_user where user_name = ? limit 1")
	if err != nil {
		log.Ob().Warn("usersignin prepare failed err:"+err.Error())
		return false
	}
	defer stmt.Close()
	rows, err := stmt.Query(username)
	if err != nil {
		log.Ob().Warn("usersignin query failed err:"+err.Error())
		return false
	}
	pRows := mydb.ParseRows(rows)
	if len(pRows)>0 && string(pRows[0]["user_pwd"].([]byte)) == pwd_enc{
		return true
	}
	return false
}

func UpdateToken(username, token string) bool {
	stmt, err := mydb.DBConn().Prepare("replace into tbl_user_token (`user_name`, `user_token`) values (?,?)")
	if err != nil {
		log.Ob().Warn("update token err:"+err.Error())
		return false
	}
	defer stmt.Close()
	_, err = stmt.Exec(username, token)
	if err != nil {
		log.Ob().Warn("update token exec err:"+err.Error())
		return false
	}
	return true
}

func TokenValid(username string, token string) bool {
	stmt, err := mydb.DBConn().Prepare("select user_token from tbl_user_token where user_name = ? limit 1")
	if err != nil {
		log.Ob().Warn("istokenvalid err:"+err.Error())
		return false
	}
	defer stmt.Close()
	var user_token string
	err = stmt.QueryRow(username).Scan(&user_token)
	if err != nil {
		log.Ob().Warn("istokenvalid query err:"+err.Error())
		return false
	}
	if user_token == token {
		return true
	}
	return false
}

func GetUserInfo(username string) (User, error) {
	user := User{}

	stmt, err := mydb.DBConn().Prepare("select user_name, signup_at from tbl_user where user_name=? limit 1")
	if err != nil {
		log.Ob().Warn("getuserinfo prepare err:"+err.Error())
		return user, err
	}
	defer stmt.Close()

	err = stmt.QueryRow(username).Scan(&user.Username, &user.SignupAt)
	if err != nil {
		log.Ob().Warn("getuserinfo queryrow err:"+err.Error())
		return user, err
	}
	return user, nil
}